#腐蚀操作

import cv2
import numpy as np

def erode_img():
    img = cv2.imread("surprise.jpg")

    #获取卷积核
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    print(kernel)

    #对每个通道进行腐蚀操作
    for i in range(3):
        img[:, :, i] = cv2.erode(img[:, :, i], kernel)

    cv2.imshow("Eroded Image", img)
    cv2.waitKey(0)

#膨胀
def dilate_img():
    img = cv2.imread("surprise.jpg")
    kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    print(kernal)
    for i in range(3):
        img[:, :, i] = cv2.dilate(img[:, :, i], kernal, iterations = 1)
    cv2.imshow("Dilated Image", img)
    cv2.waitKey(0)

#开运算  ，消除白色噪点
def opening_img():
    img = cv2.imread("surprise.jpg")
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
    cv2.imshow("morphologyEx--open Image", img)
    cv2.waitKey(0)

#闭运算  ，填充白色区域,取出白色区域内的噪点
def closing_img():
    img = cv2.imread("surprise.jpg")
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    cv2.imshow("morphologyEx——close Image", img)
    cv2.waitKey(0)

#形态学梯度  ，检测图像边缘    原图-腐蚀图 = 边缘图
def morph_gradient_img():
    img = cv2.imread("surprise.jpg")
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    img = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
    cv2.imshow("morphologyEx——gradient Image", img)
    cv2.waitKey(0)

#顶帽运算   原图-开运算 = 顶帽图    得到噪点
def tophat_img():
    img = cv2.imread("surprise.jpg")
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    img = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
    cv2.imshow("morphologyEx——tophat Image", img)
    cv2.waitKey(0)

#黑帽运算   原图 -闭运算= 黑帽图    得到白色区域内的噪点
def blackhat_img():
    img = cv2.imread("surprise.jpg")
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    img = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)
    cv2.imshow("morphologyEx——blackhat Image", img)
    cv2.waitKey(0)


if __name__ == '__main__':
    tophat_img()
    blackhat_img()